#! /usr/bin/env node
/**
 * 模版快速生成脚本,执行命令 npm run template `文件名` (会生成pages里面的页面入口 store里面的action reducer types)
 */
const glob = require('glob');
const inquirer = require('inquirer');
const program = require('commander');
const {createpage, createcomponent, updateStore} = require('./create')
const {allow} = require('./config')

// 获取指定路径下的入口文件
function getEntries(globPath) {
	let files = glob.sync(globPath) || [];
	return files;
}

function createchoicesbaseallow(allow) {
	let choices = []
	if (typeof allow == 'object') {
		allow.forEach((data) => {
			choices.push({name: data, value: `${__dirname}/../src/${data}`})
		})
	} else {
		let path = getEntries(`${__dirname}/../src/${allow}`)
		let re = `${__dirname}`
		re = re.replace(/template$/, '');
		path.map((data) => {
			let databeauty = data.replace(re, '')
			choices.push({name: databeauty, value: data})
		})
	}
	return choices
}

program
	.version(require('./../package.json').version)
	.option('-us,  --updatestore', '更新store')
	.parse(process.argv);
if (program.updatestore) {
	updateStore()
} else {
	inquirer.prompt({
		type: 'list',
		name: 'create',
		message: '想创建啥？',
		choices: [
			{
				name: '组件',
				value: 'component'
			},
			{
				name: '页面',
				value: 'page'
			}
		]
	}).then(({create}) => {
		if (create == 'component') {
			inquirer.prompt([{
				name: 'path',
				type: 'list',
				message: '请选择一级文件夹！',
				choices: allow
			}]).then(({path}) => {
				let choices = createchoicesbaseallow(path)
				inquirer.prompt([{
					name: 'pathchoose',
					type: 'list',
					message: '请选择需要塞到哪里！',
					choices: choices
				}]).then(({pathchoose}) => {
					inquirer.prompt([{
						name: 'compoentname',
						type: 'input',
						message: '请输入组件名称（例：test-component）！',
					}]).then(({compoentname}) => {
						if (compoentname) {
							createcomponent({pathchoose, compoentname})
						} else {
							console.log('别搞事情，组件名称不要为空！')
						}
					})
				})
			})
		} else if (create == 'page') {
			inquirer.prompt([{
				name: 'issub',
				type: 'list',
				message: '请选择页面类型（普通/分包）',
				choices: [{name: "普通", value: 1}, {name: "分包", value: 2}]
			}]).then(({issub}) => {
				let message = ''
				let messageChinese = ''
				if (issub == 2) {
					message = '请输入分包页面路径名称（例：test-pages）'
					messageChinese = '请输入分包页面中文名称（例：测试页面）'
				} else {
					message = '请输入页面名称（例：test-pages）'
					messageChinese = '请输入页面中文名称（例：测试页面）'
				}
				inquirer.prompt([{
					name: 'pagename',
					type: 'input',
					message: message
				}]).then(({pagename}) => {
					inquirer.prompt([{
						name: 'pagechinesename',
						type: 'input',
						message: messageChinese
					}]).then(({pagechinesename}) => {
						createpage({pagename, issub, pagechinesename})
					})
				})
			})
		}
	})
}
